﻿using System.Web.Mvc;
using NOSDC.Services;
using NOSDC.Areas.Admin.Models;
using NOSDC.Services.Extensions;

namespace NOSDC.Areas.Admin.Controllers
{
    public class ArticlesController : BaseController
    {
        private readonly IArticleService _service;

        public ArticlesController()
        {
            _service = new ArticleService();
        }

        public ArticlesController(IArticleService service)
        {
            _service = service;
        }

        //
        // GET: /Admin/Articles/
        public ActionResult Index()
        {
            var articles = _service.GetAllArticles();

            foreach (var a in articles)
                a.Story = a.Story.StripHTML();

            return View(articles);
        }

        //
        // GET: /Admin/Articles/Details/5
        public ActionResult Details(int id)
        {
            return View(_service.GetArticleByID(id));
        }

  
        // GET: /Admin/Articles/Create
        public ActionResult Create()
        {
            var article = new ArticleViewModel();
            return View(article);
        } 

    
        // POST: /Admin/Articles/Create
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(ArticleViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _service.CreateArticle(model.Article);
                    return RedirectToAction("Index");
                }
                return View(model);
            }
            catch
            {
                return View(model);
            }
        }
        
     
        // GET: /Admin/Articles/Edit/5
        public ActionResult Edit(int id)
        {
            var model = new ArticleViewModel
                            {
                                Article = _service.GetArticleByID(id)
                            };

            return View(model);
        }

        // POST: /Admin/Articles/Edit/5
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(int id, ArticleViewModel model)
        {
            try
            {
                // TODO: Add update logic here
                model.Article.ArticleID = id;
                _service.UpdateArticle(model.Article);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


        // POST: /Admin/Articles/Delete/5
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                _service.DeleteArticle(id);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
